package com.sxfq.loansupermarket.backsystem.modular.arrival.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchCustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.IScoreDetailService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.TcInfo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/scoreDetail")
public class ScoreDetailController extends BaseController {
    @Autowired
    IScoreDetailService service;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/balance/";

    /**
     * 跳转到积分明细页面
     */
    @RequestMapping("")
    public String customer(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getTcList() == null) {
            String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where b.abbreviation='"+tableHead+"' and c.name like CONCAT('%','tc','%') ";
            List<TcInfo> tcList =sqlMapper.selectList(getListSql,TcInfo.class);
            ShiroKit.getUser().setTcList(tcList);
        }
        model.addAttribute("tcList", ShiroKit.getUser().getTcList());
        model.addAttribute("sttleAccountsTime", ShiroKit.getUser().getSttleAccountsTime());
        return PREFIX + "scoreDetail.html";
    }

    /**
     * 积分明细列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object testrInfoList(SearchCustomerInfo info, HttpServletRequest request) {
        if(info.getAbbreviation()=="" || info.getAbbreviation() ==null || info.getAbbreviation()=="null"){
            return null;
        }else{
            Page<CustomerInfo> page = new PageFactory<CustomerInfo>().defaultPage();
            try {
                info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                List<CustomerInfo> list = service.selectPageListByQueryGetMap(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListByQueryGetMap(page, info);
                }
                page.setTotal(service.getQueryPagesCount(page, info));
                page.setRecords(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.packForBT(page);
        }
    }

    @RequestMapping("/sumScoreDetail")
    @ResponseBody
    public HashMap sumScoreDetail(@RequestParam(required = false) String reach,@RequestParam(required = false) String customerStatus,
                                 @RequestParam(required = false) String fieldTc,@RequestParam(required = false) String startTime,@RequestParam(required = false) String endTime) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName1 = tableHead + "customer_info";
        String sql1="";
        if (StringUtil.isNotEmpty(reach)) {
            sql1 += "  where (t2.customer_name like CONCAT('%','" + reach + "','%') or t2.customer_phone like CONCAT('%','" + reach + "','%') or " +
                    " t2.wechat_number like CONCAT('%','" + reach + "','%') or t2.medical_record_number like CONCAT('%','" + reach + "','%') " +
                    " or t2.szm like CONCAT('%','" + reach + "','%'))";
        }
        if (StringUtil.isNotEmpty(fieldTc)) {
            sql1 += " and t2.field_tc = '" + fieldTc + "'";
        }
        if (StringUtil.isNotEmpty(customerStatus)) {
            sql1 += " and t2.customer_status = '" + customerStatus + "'";
        }
        String sql = "select sum(t1.score_balance) as borrowAmount_sum " +
                " from score_deal t1 where reservations_id in (select reservations_id from " + tableName1 + " t2 "+sql1+" group by reservations_id) " +
                " and t1.add_store='"+ShiroKit.getUser().getOutpatientName()+"'";
        if (StringUtil.isNotEmpty(startTime)) {
            sql += " and t1.add_time >= '" + startTime + "'";
        }
        if (StringUtil.isNotEmpty(endTime)) {
            sql += " and t1.add_time <= '" + endTime + "'";
        }
        sql+=" limit 1";
        Map<String, Object> result = sqlMapper.selectOne(sql.toString());
        HashMap map = new HashMap();
        if (result != null) {
            map.put("borrowAmount_sum", result.get("borrowAmount_sum"));
        } else {
            map.put("borrowAmount_sum", "0");
        }
        return map;
    }


    @RequestMapping(value = "/scoreDetailExport")
    public void scoreDetailExport(@Valid SearchCustomerInfo searchInfo, HttpServletResponse response) {
        try {
            List<CustomerInfo> list = service.getscoreDetailExport(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 20; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("病历号");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("客户姓名");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("客户电话");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("客户状态");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("TC");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("积分收费方式");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("期初积分余额");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("本期积分增加");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("本期积分减少");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("期末积分余额");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("时间");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("积分备注");
            cell.setCellStyle(style);
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                CustomerInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 20; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(map.getMedicalRecordNumber());
                row.getCell(1).setCellValue(map.getCustomerName());
                if(ShiroKit.getUser().getPhonePrivilegesexp()==1) {
                    row.getCell(2).setCellValue(map.getCustomerPhone());
                }else{
                    row.getCell(2).setCellValue("无");
                }
                row.getCell(3).setCellValue(map.getCustomerStatus());
                row.getCell(4).setCellValue(map.getFieldTc());
                row.getCell(5).setCellValue(map.getModeName());
                row.getCell(6).setCellValue(map.getMoneyBalance());
                if ("充值".equals(map.getModeName()) ) {
                    row.getCell(7).setCellValue(Double.parseDouble(map.getScoreBalance()));
                } else {
                    row.getCell(7).setCellValue(0);
                }
                if ("消费".equals(map.getModeName())||"退积分".equals(map.getModeName())) {
                    row.getCell(8).setCellValue(0-Double.parseDouble(map.getScoreBalance()));
                } else {
                    row.getCell(8).setCellValue(0);
                }
                row.getCell(9).setCellValue(map.getMoneyBalance()+Double.parseDouble(map.getScoreBalance()));
                row.getCell(10).setCellValue(map.getAddTime());
                row.getCell(11).setCellValue(map.getRemarks());
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}